<template>
  <div class="app-container">
    <el-dialog
      :title="id ? '修改' : '新增'"
      :visible.sync="visible"
      width="800px"
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="架层编号" prop="caseNo">
          <el-input v-model="form.caseNo" :disabled="id ? true : false" />
        </el-form-item>
        <el-form-item label="架层名称" prop="caseName">
          <el-input v-model="form.caseName" />
        </el-form-item>
        <el-form-item label="书架" prop="posId">
          <el-select
            v-model="form.posId"
            placeholder="请选择书架"
            clearable
            filterable
            remote
            :remote-method="remoteMethod"
            size="small"
            @clear="handleClear"
          >
            <el-option
              v-for="dict in posArr"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="side">
          <el-select
            v-model="form.side"
            placeholder="请选择方向"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in sideArr"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import editorCom from '@/components/Editor'
import { positionArr } from '@/api/model'
import { addCase, editCase } from '@/api/case'
import { sideArr } from '@/utils/config-type'
export default {
  name: 'Add',
  components: {
    editorCom
  },
  props: {
    id: {
      type: [Number, String],
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    objTarget: {
      type: String,
      default: ''
    }
  },
  data() {
    // 定义校验规则
    const validateCaseNo = (rule, value, callback) => {
      if (!value) {
        callback(new Error('架层编号不能为空'))
      } else {
        callback()
      }
    }
    const sideArrData = sideArr
    return {
      form: {},
      rules: {
        caseNo: [
          { required: true, validator: validateCaseNo, trigger: 'blur' }
        ],
        caseName: [
          { required: true, message: '架层名称不能为空', trigger: 'blur' }
        ],
        posId: [{ required: true, message: '请选择书架', trigger: 'change' }],
        side: [{ required: true, message: '请选择方向', trigger: 'change' }]
      },
      posArr: [],
      sideArr: sideArrData
    }
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.giveDetail()
        }
      },
      deep: false,
      immediate: true
    },
    visible: {
      handler(val) {
        if (val) {
          this.requestpositionArr()
        }
      },
      deep: false,
      immediate: true
    }
  },
  methods: {
    handleClear() {
      this.requestpositionArr('')
    },
    remoteMethod(query) {
      this.requestpositionArr(query)
    },
    requestpositionArr(name) {
      this.posArr = []
      positionArr('Shelf', name)
        .then((res) => {
          if (res.success) {
            const arr = res?.data ?? []
            if (arr.length > 0) {
              arr.map((item) => {
                const obj = {
                  label: item?.posName ?? '',
                  value: item?.posId ?? ''
                }
                this.posArr.push(obj)
              })
            }
          }
        })
        .catch((err) => {})
    },
    giveDetail() {
      const objTarget = JSON.parse(this.objTarget)
      this.form = {
        caseNo: objTarget.caseNo,
        caseName: objTarget.caseName,
        posId: objTarget.posId,
        side: objTarget.side
      }
    },
    cancle() {
      this.handleClose(false)
    },
    sub() {
      // 触发表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验通过，执行提交逻辑
          let requestWay, msg, errmsg
          const queryParams = {
            caseNo: this.form.caseNo,
            caseName: this.form.caseName,
            posId: this.form.posId,
            side: this.form.side
          }
          if (this.id) {
            requestWay = editCase
            queryParams.caseId = this.id
            msg = '修改成功'
            errmsg = '修改失败'
          } else {
            requestWay = addCase
            msg = '新增成功'
            errmsg = '新增失败'
          }
          console.log('提交表单数据:', queryParams)
          requestWay(queryParams)
            .then((res) => {
              if (res.success) {
                this.$message.success(msg)
                this.handleClose(true)
              } else {
                this.$message.error(errmsg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          console.log('表单校验未通过')
          return false
        }
      })
    },
    handleClose(status) {
      this.form = {}
      this.imageOidList = []
      // 重置表单
      this.$refs.form.resetFields()
      this.$emit('update:visible', false)
      this.$emit('close', status === true ? status : false)
    }
  }
}
</script>

<style scoped>
</style>
